<template>
  <div class="app-audioplayer-play">
    <div
      class="app-audioplayer-play-btn"
      @click="playOrPause"
    >
      <i
        v-if="pause"
        class="material-icons"
      >play_circle_filled</i>
      <i
        v-else
        class="material-icons"
      >pause_circle_filled</i>
    </div>
    <Slider
      v-model="sliderSet"
      class="app-audioplayer-slider"
      :max="sliderMax"
      :tip-format="sliderTipFromater"
      @on-change="handleSiderChange"
    />
    <span>{{ seek }} / {{ duration }}</span>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { Howl, Howler } from 'howler'
import { formateDurationOfSong } from '@/utils'

@Component({
  name: 'SongPlayer'
})
export default class extends Vue {
  @Prop(String) readonly src!: string

  private player: Howl = new Howl({
    src: [this.src],
    html5: true,
    onload: this.handlePlayerLoaded,
    onplay: this.handlePlayingStep,
    onend: this.handleEnded,
    onseek: this.handlePlayingStep
  })

  private seek = '--:--';
  private sliderSet = 0;
  private sliderMax = 0;
  private readonly sliderGranularity = 0.5 // second
  private pause = true;

  get duration () {
    return formateDurationOfSong(this.player.duration())
  }

  private sliderTipFromater (step: number) {
    return (this.seek = formateDurationOfSong(Math.floor(step * this.sliderGranularity)))
  }

  private playOrPause () {
    this.pause
      ? this.player.play()
      : this.player.pause()
    this.pause = !this.pause
  }

  private handlePlayerLoaded () {
    this.sliderMax = this.player.duration() / this.sliderGranularity
  }

  private handlePlayingStep () {
    this.sliderSet = this.player.seek() as number / this.sliderGranularity

    // this.seek = formateDurationOfSong(this.sliderSet)
    if (this.player.playing()) {
      requestAnimationFrame(this.handlePlayingStep.bind(this))
    }
  }

  private handleEnded () {
    this.pause = true
  }

  private handleSiderChange (step: number) {
    this.player.seek(step * this.sliderGranularity)
  }
}
</script>

<style lang="less" scoped>

.app-audioplayer-play {
  padding: 8px !important;
  display: flex;
  justify-content: space-between;
  align-items: center;
  div, span {
    display: inline-block;
  }
}

.app-audioplayer-play-btn>i {
  cursor: pointer;
  font-size: 38px;
}

.app-audioplayer-slider {
  // width: 70%;
  flex-grow: 1;
  padding: 0 18px;
}

</style>
